﻿using System;
using System.Collections.Generic;
using NHibernate.Mapping.ByCode;
using Xenta.Enums;
using Xenta.Utils;

namespace Xenta.Entities
{
    /// <summary>
    /// Represents the role entity.
    /// </summary>
    /// <remarks><pre>
    /// The entity regarding the disclosure level.
    /// 
    /// + Entire
    ///  | - Permissions(of the Extended level)
    ///  + Extended
    ///   + Base
    ///    | - Name
    ///    | - Flags
    ///    | - UpdatedOn
    ///    | - CreatedOn
    ///    + Keys
    ///     | - Code
    ///     + Primary
    ///      | - EntityID
    /// 
    /// Note: upper level includes lower level.
    /// </pre></remarks>
    public class RoleEntity : AuditableEntity,
        IRelationHolder<PermissionEntity>
    {
        #region Fields

        private ICollection<AccountEntity> _accounts;
        private ICollection<PermissionEntity> _permissions;

        #endregion

        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public RoleEntity()
        {
            _accounts = new List<AccountEntity>();
            _permissions = new List<PermissionEntity>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public virtual string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public virtual string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public virtual RoleFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Collections

        /// <summary>
        /// Gets or sets the collection of accounts.
        /// </summary>
        public virtual ICollection<AccountEntity> Accounts
        {
            get
            {
                return _accounts;
            }
            set
            {
                _accounts = value;
            }
        }

        /// <summary>
        /// Gets or sets the collection of permissions.
        /// </summary>
        public virtual ICollection<PermissionEntity> Permissions
        {
            get
            {
                return _permissions;
            }
            set
            {
                _permissions = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Maps a permission to the role.
        /// </summary>
        /// <param name="child">The permission to map.</param>
        public virtual void Map(PermissionEntity child)
        {
            if(Permissions.Contains(child))
                return;
            Permissions.Add(child);
        }

        /// <summary>
        /// Unmaps the permission from the role.
        /// </summary>
        /// <param name="child">The permission to unmap.</param>
        public virtual void Unmap(PermissionEntity child)
        {
            if(!Permissions.Contains(child))
                return;
            Permissions.Remove(child);
        }

        #endregion

        #region Utilities

        protected override void Disclose(IDictionary<String, Object> obj,
            DisclosureLevel level,
            IDictionary<String, String> options)
        {
            base.Disclose(obj, level, options);
            if(level >= DisclosureLevel.Keys)
                obj["Code"] = Code;
            if(level >= DisclosureLevel.Base)
            {
                obj["Name"] = Name;
                obj["Flags"] = Flags.ToString();
            }
            if(level >= DisclosureLevel.Entire)
                obj["Permissions"] = Permissions.Map(x => x.Disclose(DisclosureLevel.Extended, options));
        }

        #endregion
    }

    /// <summary>
    /// The entity NHibernate mapper.
    /// </summary>
    public class RoleMapping : EntityMapping<RoleEntity>
    {
        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public RoleMapping()
        {
            Table("fwk_Roles");
            Id(x => x.EntityID, m =>
            {
                m.Column("RoleID");
                m.Generator(Generators.Identity);
            });
            Property(x => x.Code, m =>
            {
                m.Unique(true);
                m.Index("IX_fwk_Roles");
                m.NotNullable(true);
                m.Length(10);
                m.Column(c =>
                {
                    c.SqlType("nvarchar(10)");
                });
            });
            Property(x => x.Name, m =>
            {
                m.NotNullable(true);
                m.Length(100);
                m.Column(c =>
                {
                    c.SqlType("nvarchar(100)");
                });
            });
            Property(x => x.Flags, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.CreatedOn, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.UpdatedOn, m =>
            {
                m.NotNullable(true);
            });
            Bag(x => x.Accounts, m =>
            {
                m.Table("fwk_MAccountRoles");
                m.Key(k =>
                {
                    k.Column("RoleID");
                    k.ForeignKey("FK_fwk_MAccountRoles_fwk_Roles");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("AccountID");
                    m.ForeignKey("FK_fwk_MAccountRoles_fwk_Accounts");
                });
            });
            Bag(x => x.Permissions, m =>
            {
                m.Table("fwk_MRolePermissions");
                m.Key(k =>
                {
                    k.Column("RoleID");
                    k.ForeignKey("FK_fwk_MRolePermissions_fwk_Roles");
                    k.NotNullable(true);
                });
            },
            a =>
            {
                a.ManyToMany(m =>
                {
                    m.Column("PermissionID");
                    m.ForeignKey("FK_fwk_MRolePermissions_fwk_Permissions");
                });
            });
            Cache(m =>
            {
                m.Usage(CacheUsage.ReadWrite);
            });
            Cache(m =>
            {
                m.Usage(CacheUsage.ReadWrite);
            });
        }
    }
}
